const response = require('../../utils/response');
const { handleDatabaseError } = require('../../utils/dberrordeal');
const collectService = require('../../services/good/collectService');
class CollectController {
    static async getCollectList(ctx) {
        const data = ctx.request.body || {};
        const { pageNum = 1, pageSize = 10 } = data;
 
        const res = await collectService.getCollectList({ pageNum, pageSize }, {userId: ctx.userId});
        res ? response.success(ctx, { data: res }) : response.error(ctx, {});
    }
    static async createCollect(ctx) {
        const collectData = ctx.request.body;
        //如果存在相同的userIdHE goodId则不允许添加
        const existCollect = await collectService.getCollectByGoodId(collectData.goodId, ctx.userId);
        if (existCollect) {
            return response.error(ctx, { message: '收藏已存在' });
        }
        await collectService.createCollect({ ...collectData, userId: ctx.userId })
            .then(() => response.success(ctx, {}))
            .catch(err => handleDatabaseError(ctx, err, '收藏名称重复'));
    }
    static async cancelCollect(ctx) {
        const collectData = ctx.request.body;
        try {
            const result = await collectService.deleteCollect(collectData.goodId, ctx.userId);
            if (result) {
                response.success(ctx, {});
            } else {
                response.error(ctx, { message: '取消收藏失败，未找到对应收藏记录' });
            }
        } catch (err) {
            handleDatabaseError(ctx, err, '取消收藏失败');
        }
    }
}
module.exports = CollectController;